package com.audaque.springboot.foshanupload.web.nosaveframeworklogin.filter;

import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.authcore.service.inface.UserService;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.audaque.springboot.foshanupload.core.properties.SwitchProperties;
import com.audaque.springboot.foshanupload.core.result.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
public class UsernamePasswordLoginFilter implements Filter {
    @Autowired
    private SwitchProperties switchProperties;
    @Autowired
    private UserService userService;


    @Value("${db.tenantId}")
    private String tenantId;


    @Override
    public void doFilter(final ServletRequest req,
                         final ServletResponse res,
                         final FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String url = request.getRequestURL().toString();
        log.debug("url：" + url);
        String contentType = request.getContentType();
        log.debug("contentType：" + contentType);
        String username = request.getParameter("username");
        log.debug("username：" + username);
        String password = request.getParameter("password");
        log.debug("password：" + password);
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = new TransmittableThreadLocalCurrentUser();
            transmittableThreadLocalCurrentUser.setUsername(username);
            transmittableThreadLocalCurrentUser.setPassword(password);
            //校验登录表单
            Boolean successYn = userService.validLoginForm(transmittableThreadLocalCurrentUser);
            if (successYn) {
                //登录成功处理
                String userId = userService.getUserIdByUsername(username);
                TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser1 = new TransmittableThreadLocalCurrentUser();
                transmittableThreadLocalCurrentUser1.setId(userId);
                transmittableThreadLocalCurrentUser1.setTenantId(tenantId);
                transmittableThreadLocalCurrentUser1.setUsername(username);

                //父子线程传递上下文（用户信息）,  TransmittableThreadLocal，避免重复解析用户
                TransmittableThreadLocalCurrentUser.setCurrentUser(transmittableThreadLocalCurrentUser1);


                Thread thread = Thread.currentThread();
                long threadId = thread.getId();
                log.debug(String.format("线程id:%s", threadId));


            }

        }

        chain.doFilter(req, res);
        return;
    }

}
